<?php

namespace app\controllers;

use app\library\ClientInfo;
use app\library\IP;
use app\library\Number;
use app\library\ResultJson;
use app\library\StringPlus;
use app\models\ShortUrlBrowseLog;
use app\models\ShortUrlList;
use app\models\ShortUrlUser;
use Phalcon\Http\Response;

/**
 * 短链服务处理
 * @package app\controllers
 */
class ShorturlController extends ControllerBase
{
    /**
     * cookie key
     */
    const COOKIE_KEY = 'shorturl_user';
    /**
     * 登录用户的信息
     * @var array
     */
    private $userInfo;

    public function initialize()
    {
        if ($this->cookies->has(static::COOKIE_KEY)) {
            $cookeValue = $this->cookies->get(static::COOKIE_KEY)->getValue();
            $this->userInfo = json_decode($cookeValue, true);
            if ($this->userInfo) {
                $this->view->userInfo = $this->userInfo;
                return;
            }
        }

        $this->userInfo = false;
        if (!in_array($this->router->getActionName(), ['login',])) {
            $this->response->redirect('shorturl/login');
        }
    }

    /**
     * 列表
     */
    public function indexAction()
    {
        $this->view->urlList = ShortUrlList::query()
            ->where('userId = :uid:', ['uid' => $this->userInfo['id']])
            ->execute();
        $this->getDI()->setShared('numberCrypt', function () {
            return Number::getInstance($this);
        });
    }

    /**
     * 添加
     * @return $this|ResultJson
     */
    public function appendAction()
    {
        $req = $this->request;
        $resp = new ResultJson();
        if ($req->isPost() == false) {
            return $resp->sendError(0, '错误请求!');
        }
        $url = $req->getPost('url');
        if (empty($url)) {
            return $resp->sendError(0, '参数异常!');
        }
        if (!(StringPlus::startsWith($url, 'http://') || StringPlus::startsWith($url, 'https://'))) {
            return $resp->sendError(0, '参数异常!');
        }
        $urlInfo = new ShortUrlList();
        $urlInfo->userId = $this->userInfo['id'];
        $urlInfo->original = $url;
        if ($urlInfo->create() == false) {
            return $resp->sendError(0, '保存数据异常!');
        }
        $resultInfo = ShortUrlList::findFirst('urlId = ' . $urlInfo->urlId)->toArray();
        $resultInfo['id'] = Number::getInstance($this->getDI())->numberEncode($resultInfo['urlId']);
        return $resp->sendResult($resultInfo);
    }

    /**
     * 设置标题
     * @return $this
     */
    public function settitleAction()
    {
        $req = $this->request;
        $resp = new ResultJson();
        if ($req->isPost() == false) {
            return $resp->sendError(0, '错误请求!');
        }
        $id = $req->getPost('id');
        $title = $req->getPost('title');
        $info = ShortUrlList::findFirst('urlId = ' . $id);
        if ($info != null) {
            // add click
            $info->title = $title;
            $info->update();
        }
        return $resp->sendResult(1);
    }

    /**
     * 跳转到原始URL地址
     * @param null|string $id
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|void
     */
    public function originalAction($id = null)
    {
        $numbers = Number::getInstance($this->getDI())->numberDecode($id);
        if (count($numbers) == 0) {
            //throw new Exception('id not find.');
            //$this->response->redirect('-404')->sendHeaders();
            echo 'id not find.';
            return;
        }
        $id = $numbers[0];
        $urlInfo = ShortUrlList::getInfoAndAddClicks($id);
        if ($urlInfo == null) {
            echo 'id not find.';
            return;
        }
        // save log
        $referer = $this->request->getHTTPReferer();
        $referer = empty($referer) ? ' ' : $referer;
        ShortUrlBrowseLog::addLog($urlInfo->urlId, ClientInfo::instance()->getClientId(), IP::UserIp(), $referer, $this->request->getUserAgent());
        return $this->response->redirect($urlInfo->original);
    }

    /**
     * 登录
     * @return Response
     */
    public function loginAction()
    {
        $req = $this->request;
        if ($req->isPost() == false) {

        } else {
            $account = $req->getPost('account');
            $password = $req->getPost('password');
            $result = new ResultJson();
            // 验证登录
            $userInfo = ShortUrlUser::login($account, $password);
            if ($userInfo == false) {
                $result->sendError(0, '账号或密码错误!');
            } else {
                $result->sendResult(['success' => 1]);
                $this->userInfo = [
                    'id' => $userInfo->userId,
                    'name' => $userInfo->userName,
                    'time' => time(),
                ];
                $this->cookies->set(static::COOKIE_KEY, json_encode($this->userInfo));
                $this->cookies->send();
            }
            return $result;
        }
    }
}

